<?php
namespace app\index\controller\xilujob;

use app\common\controller\xilujob\Xilujob;
use app\common\model\xilujob\Area;
use app\common\model\xilujob\Banner;
use app\common\model\xilujob\Benefit;
use app\common\model\xilujob\CompanyProperties;
use app\common\model\xilujob\CompanyScale;
use app\common\model\xilujob\CompanyStatistics;
use app\common\model\xilujob\EducationLevel;
use app\common\model\xilujob\EnterpriseInfo;
use app\common\model\xilujob\Job;
use app\common\model\xilujob\JobApply;
use app\common\model\xilujob\JobCategory;
use app\common\model\xilujob\JobInterview;
use app\common\model\xilujob\Resume;
use app\common\model\xilujob\IndustryCategory;
use app\common\model\xilujob\ResumeActionLog;
use app\common\model\xilujob\ResumeDownload;
use app\common\model\xilujob\Salary;
use app\common\model\xilujob\SiteCity;
use app\common\model\xilujob\UserCollection;
use app\common\model\xilujob\UserFeedback;
use app\common\model\xilujob\WorkExperience;
use app\common\model\xilujob\XilujobUser;
use app\index\library\Paginator;
use app\index\model\xilujob\PersonalMessage;
use app\index\model\xilujob\SystemMessage;
use think\Config;
use think\Cookie;
use think\Db;
use think\db\Query;
use think\Exception;
use think\Hook;
use think\Validate;
use function fast\array_get;

/**
 * pc插件控制器基类
 */
class User extends Xilujob
{

    protected $layout = '';
    protected $noNeedLogin = ['switch_city', 'register', 'third'];
    protected $noNeedEnterpriseAudit = ['logout'];
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize();
        $auth = $this->auth;

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'), '/');
        }

        //监听注册登录退出的事件
        Hook::add('user_login_successed', function ($user) use ($auth) {
            $expire = input('post.keeplogin') ? 30 * 86400 : 0;
            Cookie::set('uid', $user->id, $expire);
            Cookie::set('token', $auth->getToken(), $expire);
        });
        Hook::add('user_register_successed', function ($user) use ($auth) {
            Cookie::set('uid', $user->id);
            Cookie::set('token', $auth->getToken());
        });
        Hook::add('user_delete_successed', function ($user) use ($auth) {
            Cookie::delete('uid');
            Cookie::delete('token');
        });
        Hook::add('user_logout_successed', function ($user) use ($auth) {
            Cookie::delete('uid');
            Cookie::delete('token');
        });
    }

    /**
     * 注销登录
     */
    public function logout()
    {
        //注销本站
        $this->auth->logout();
        $this->success(__('Logout successful'), url('index/user/login'));
    }




    //个人中心
    public function home(){
        $this->assign('menu_tag','home');
        $this->assign('title', '个人中心');
        $user = $this->auth->getUser();
        $xilujob_user = \app\common\model\xilujob\XilujobUser::get(['user_id'=>$user->id]);
        switch ($xilujob_user->group_id) {
            case \app\common\model\xilujob\XilujobUser::GROUP_MEMBER:
                return $this->home_personal();
            case \app\common\model\xilujob\XilujobUser::GROUP_COMPANY:
//            case \app\common\model\User::GROUP_LABOUR:
                return $this->home_company();
//            case \app\common\model\User::GROUP_TRAINER:
//                return $this->home_trainer();
            default:
                return '';
        }
    }

    protected function home_company() {
        $jobCount = Job::where('publisher_id', $this->company->id)->count();
        $jobLimit = EnterpriseInfo::where('id',$this->company->id)->value('job_num_limit');
        $this->assign('job_count',$jobCount);
        $this->assign('job_limit', $jobLimit);
        $statistics = CompanyStatistics::get(['company_id'=>$this->company->id]);
        $applyCount = JobApply::where('company_id', $this->company->id)
            ->count('distinct user_id');
        $interviewCount = JobInterview::where('company_id', $this->company->id)
            ->count('distinct user_id');
        $interviewToday = JobInterview::where('company_id', $this->company->id)
            ->whereTime('interview_time','d')
            ->count('distinct user_id');
        $interviewTomorrow = JobInterview::where('company_id', $this->company->id)
            ->whereBetween('interview_time',[strtotime('tomorrow'), strtotime('tomorrow')+86399])
            ->count('distinct user_id');
        $interviewMonth = JobInterview::where('company_id', $this->company->id)
            ->whereTime('interview_time','m')
            ->count('distinct user_id');
        $recommendResumes = Resume::recommendResumes($this->auth->getUser(),$this->company, ['pagesize'=>2])['resumes'];
        $this->assign('statistics', $statistics);
        $this->assign('apply_count', $applyCount);
        $this->assign('interview_count',$interviewCount);
        $this->assign('interview_today', $interviewToday);
        $this->assign('interview_tomorrow', $interviewTomorrow);
        $this->assign('interview_month', $interviewMonth);
        $this->assign('ad', Banner::getBannerRandom('enterprise_home',$this->city->id,false));
        $this->assign('recommend_resumes', $recommendResumes);
        return $this->fetch('home_company');
    }

    /**
     * 消息类型
     */
    public function message() {
        $user = $this->auth->getUser();
        $xilujob = XilujobUser::get(['user_id'=>$user->id]);
        $personalMessage = PersonalMessage::where('user_id', $user->id)
            ->order('id', 'desc')
            ->find();
        $activityMessage = SystemMessage::where('type', SystemMessage::TYPE_ACTIVITY)
            ->order('id', 'desc')
            ->find();
        $systemMessage = SystemMessage::where('type', SystemMessage::TYPE_SYSTEM)
            ->order('id', 'desc')
            ->find();
        $data = [
            'personal'=>['total'=>$xilujob->personal_message,'message'=>$personalMessage],
            'activity'=>['total'=>$xilujob->activity_message,'message'=>$activityMessage],
            'system'=>['total'=>$xilujob->system_message,'message'=>$systemMessage]
        ];
        $this->assign('personal', $data['personal']);
        $this->assign('activity', $data['activity']);
        $this->assign('system', $data['system']);
        $this->assign('title', '消息中心');
        $this->assign('menu_tag', 'notification');
        return $this->fetch();
    }

    /**
     * 消息列表
     */
    public function personal_messages() {
        $xilujobuser = XilujobUser::get(['user_id'=>$this->auth->id]);
        if($xilujobuser->personal_message>0) {
            $xilujobuser->save(['personal_message'=>0]);
        }
        $list = PersonalMessage::where('user_id', $this->auth->id)
            ->order('id','desc')
            ->paginate();

        foreach($list as $item) {
            switch ($item['type']) {
                case PersonalMessage::TYPE_RESUME_VIEWED:
                    $item->url = url('xilujob.user/view_me_personal');
                    break;
                case PersonalMessage::TYPE_APPLY_SENT:
                    $item->url = url('xilujob.user/job_applies');
                    break;
                case PersonalMessage::TYPE_APPLY_REJECTED:
                    $item->url = url('xilujob.user/my_applies');
                    break;
                case PersonalMessage::TYPE_INTERVIEW_SENT:
                    $item->url = url('xilujob.user/interview_invitation');
                    break;
                case PersonalMessage::TYPE_INTERVIEW_REJECTED:
                    $item->url = url('xilujob.user/company_interviews',['status'=>1]);
                    break;
                case PersonalMessage::TYPE_INTERVIEW_ACCEPTED:
                    $item->url = url('xilujob.user/company_interviews',['status'=>2]);
                    break;
                case PersonalMessage::TYPE_INTERVIEW_FAILED:
                    $item->url = url('xilujob.user/interview_invitation');
                    break;
                case PersonalMessage::TYPE_INTERVIEW_PASSED:
                    $item->url = url('xilujob.user/interview_invitation');
                    break;

            }
        }

        $this->assign('messages', $list);
        $this->assign('title','消息中心');
        $this->assign('menu_tag', 'notification');
        return $this->fetch();
    }

    public function activity_messages() {
        $user  =$this->auth->getUser();
        $xilujobuser = XilujobUser::get(['user_id'=>$user->id]);
        if($xilujobuser->activity_message>0) {
            $xilujobuser->save(['activity_message'=>0]);
        }
        $list = SystemMessage::where('type', SystemMessage::TYPE_ACTIVITY)
            ->order('id','desc')
            ->paginate();
        $this->assign('messages', $list);
        $this->assign('title','消息中心');
        $this->assign('menu_tag', 'notification');
        return $this->fetch('activity_messages');
    }

    public function system_messages() {
        $user  =$this->auth->getUser();
        $xilujobuser = XilujobUser::get(['user_id'=>$user->id]);
        if($xilujobuser->system_message>0) {
            $xilujobuser->save(['system_message'=>0]);
        }
        $list = SystemMessage::where('type', SystemMessage::TYPE_SYSTEM)
            ->order('id','desc')
            ->paginate();
        $this->assign('messages', $list);
        $this->assign('title','消息中心');
        $this->assign('menu_tag', 'notification');
        return $this->fetch('system_messages');
    }


    public function job_categories() {
        $tree = \app\admin\model\xilujob\JobCategory::getCategoryTree();
        $arr = $tree->getTreeArray(0);
        $this->success('','',$arr);
    }

    public function feedback() {
        if($this->request->isPost()) {
            $params = $this->request->post('',null,'trim,strip_tags');
            $feedback = new UserFeedback();
            $params['user_id'] = $this->auth->id;
            $params['images'] = is_array(array_get($params, 'images', [])) ? implode(',', array_get($params, 'images', [])) : '';
            $validator = new \app\common\validate\xilujob\UserFeedback();
            if(!$validator->check($params)){
                $this->error($validator->getError());
            }
            $ret = $feedback->save($params);
            if($ret===false) {
                $this->error($feedback->getError());
            }
            $this->success();
        }
        $reason = Config::get('site.feedback_reason') ?? ["1"=>"注册登录","2"=>"求职","3"=>"招聘"];
        $this->assign('menu_tag', 'feedback');
        $this->assign('title','意见反馈');
        return $this->fetch('',['feedback_reasons'=>$reason]);
    }

}